package com.yonyou.pmclouds.organization.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.SqlUtil;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.mapper.OrganizationMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class OrgInsertCheckProcessor implements MultiProcessor<OrganizationVO>{

    private OrganizationMapper mapper;

    public OrgInsertCheckProcessor(OrganizationMapper mapper){
        this.mapper = mapper;
    }

    @Override
    public void process(OrganizationVO[] vos, OrganizationVO[] origs) throws BusinessException {
        if(ArrayUtils.isEmpty(vos)){
            return;
        }
        List<String> codes  = new ArrayList<>();
        for(OrganizationVO vo : vos){
            if(vo != null){
                if(StringUtils.isEmpty(vo.getScode())){
                    throw new BusinessException("组织编码不能为空！");
                }
                if(StringUtils.isEmpty(vo.getSname())){
                    throw new BusinessException("组织名称不能为空！");
                }
                codes.add(vo.getScode());
            }
        }
        OrganizationVO[] result = mapper.getOrgByCode(RuntimeEnvironment.getTenantId(), SqlUtil.getSqlIn(codes.toArray(new String[0])));
        StringBuffer errorMsg = new StringBuffer();
        if(ArrayUtils.isNotEmpty(result)){
            errorMsg.append("组织编码重复，重复的编码为：");
            for(int i = 0; i < result.length; i++){
                if(result[i] != null) errorMsg.append(result[i].getScode() + (i == result.length - 1 ? "。" : "，"));
            }
            throw new BusinessException(errorMsg.toString());
        }
    }
}
